package org.myhibernate.core.method;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

import org.myhibernate.cache.CacheContainer;
import org.myhibernate.cache.CacheContainers;
import org.myhibernate.cache.RemoveSqlCaches;
import org.myhibernate.core.method.CacheQuery;
import org.myhibernate.core.method.GenericMethod;
import org.myhibernate.db.DataHelper;

public class AddMethod<T> extends GenericMethod<T>
{
	private CacheQuery cacheQuery=null;
	public void init(Class cls, Connection connection) 
	{
		super.init(cls, connection);
		cacheQuery=new CacheQuery(connection, cls); 
	}
	@Override 
	public void init(Class cl, DataHelper helper) {
		super.init(cl, helper);
		cacheQuery=new CacheQuery(cl, helper);
	}
	@Override
	public void init(Class cl, Connection connection, DataHelper helper) {
		super.init(cl, connection, helper);
		cacheQuery=new CacheQuery(cl, connection, helper);
	}
	public Object execute(Object obj, Map<String, Object> map) throws Exception 
	{
		if (getBuffer().length()>0) {
			getBuffer().delete(0,getBuffer().length());
		}
		boolean flag=false;
		//add to cache
		PropertyDescriptor descriptor=null;
		 descriptor= new PropertyDescriptor(getMapping().getId_Field(), getCl());
		 Method rM = descriptor.getReadMethod();
		 Object idValue=rM.invoke(obj);
		
		// add to database
		try {
			List<String> fieldList=getMapping().getPropertyList();
			String fieldName="";
			Object value=null;
			getBuffer().append("insert into "+getMapping().getTable()+"("+getMapping().getColumns()+") values(");
			for (int i = 0; i < fieldList.size(); i++) 
			{
				fieldName=fieldList.get(i);
				try {  
					//System.out.println("fieldName="+fieldName+",getCl()="+getCl()+",obj="+obj+",get="+getMapping().getPropertyGetList().get(i));
					 rM=getCl().getDeclaredMethod(getMapping().getPropertyGetList().get(i));
					 value=rM.invoke(obj);
					 if (0==i)
					 {
						 getBuffer().append(getHandle().handle(value));
					} else {
						getBuffer().append(","+getHandle().handle(value));
					}
				} catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException(e.toString());
				}
			}//endfor
			getBuffer().append(")");
			String sql=getSql();
			try {
				cacheQuery.executeSql(sql);
				CacheContainer cacheContainer=CacheContainers.getCache(getCl());
				cacheContainer.set(idValue, obj);
				new RemoveSqlCaches(getCl());
				flag=true;
			} catch (Exception e) 
			{
				e.printStackTrace();
				throw new RuntimeException(e.toString());
			}finally{
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.toString());
		}	
			return flag;
	}
	public void close() {
		cacheQuery.close();
	}
}
